package de.baumann.browser.views.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Message
import de.baumann.browser.R
import de.baumann.browser.views.widget.captcha.Captcha
import de.baumann.browser.views.widget.captcha.RedCaptchaStrategy
import kotlinx.android.synthetic.main.dialog_captcha.*

/**
*@author:
*@date:2019/7/10 16:53
*@discription: 领红包 滑块验证
*/
class CaptchaDialog(context: Context, var callback: CaptchaCallback) : BaseDialog(context) {
    override fun laoutId(): Int {
        return R.layout.dialog_captcha
    }

    override fun initView() {
        captCha.setCaptchaStrategy(RedCaptchaStrategy(context,300,100))

        captCha.setCaptchaListener(object : Captcha.CaptchaListener {
            override fun onAccess(time: Long): String {
                handler.sendEmptyMessageDelayed(0, 1000)
                return context.getString(R.string.Verification_passed)
            }

            override fun onFailed(failCount: Int): String {
                handler.sendEmptyMessageDelayed(1, 1000)
                return context.getString(R.string.verification_failed)
            }

            override fun onMaxFailed(): String {
                handler.sendEmptyMessageDelayed(2, 1000)
                return context.getString(R.string.many_failures)
            }
        })
    }

    private val handler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            when (msg?.what) {

                0 -> {
                    dismiss()
                    callback.onAccess()
                }

                1 -> {
                    captCha.reset(false)
                }

                2 -> dismiss()
            }
        }
    }

    interface CaptchaCallback {
        fun onAccess()
    }

}